package cn.wzl.recognition.training;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class CVSFileLoader {

    private final List<String> lineInfo;
    private final double [][] data;

    public CVSFileLoader(String fileName) throws IOException {
        BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
        this.lineInfo = new ArrayList<>();
        String line;
        while((line = fileReader.readLine()) != null) {
            lineInfo.add(line);
        }
        this.data = new double[lineInfo.size()][];
        for (int i = 0; i < lineInfo.size(); i ++) {
            data[i] = transferStringToDoubleList(lineInfo.get(i));
        }
    }

    private double[] transferStringToDoubleList(String csvLine) {
        String [] cells = csvLine.split(",");
        double [] doubleCells = new double[cells.length];
        for(int i = 0; i < cells.length; i ++) {
            doubleCells[i] = Double.parseDouble(cells[i]);
        }
        return doubleCells;
    }


    public int retrieveColumnsSize() {
        return Optional.ofNullable(lineInfo.get(0))
                .map(s -> s.split(","))
                .map(ss -> ss.length)
                .orElse(0);
    }


    public int retrieveRowSize() {
        return lineInfo.size();
    }


    public double[][] getData() {
        return data;
    }

    public List<String> getLineInfo() {
        return lineInfo;
    }

}
